#include<iostream>
#include<pthread.h>
#include<stdlib.h>
#include<time.h>
#include<unistd.h>

pthread_cond_t Signal;
class MyMutex{
  public:
  int ticket = 100;
  pthread_mutex_t mtx;
  MyMutex()
  {
    pthread_mutex_init(&mtx,nullptr);
  }
  ~MyMutex(){
    pthread_mutex_destroy(&mtx);
  }
};
MyMutex Mutex;
void* Boss(void* args){
  std::cout << args << std::endl;
  while(true)
  {
      pthread_cond_signal(&Signal);
      //usleep(3);
  }
  return nullptr;

}
void* DoWork(void* args)
{
  int* id = (int*)args;
  pthread_mutex_lock(&Mutex.mtx);
  while(true)
  {
    std::cout << "i am " << *id << " ";
    pthread_cond_wait(&Signal,&Mutex.mtx);
   if(Mutex.ticket > 0)
   {
     std::cout << "ticket have " << Mutex.ticket-- << " ";
     std::cout << " success have ticket" << std::endl;
   }
   else{
      pthread_mutex_unlock(&Mutex.mtx);
      break;
   }
      pthread_mutex_unlock(&Mutex.mtx);
  }
  return nullptr;

}
int main()
{
  pthread_t boos;
  if(pthread_create(&boos,nullptr,Boss,(void*)"boos") != 0)
  {
    perror("create pthread error");
  }
  pthread_cond_init(&Signal,nullptr);

  pthread_t worker[5];
  for(int i = 0;i<5;i++){
      if(pthread_create(worker+i,nullptr,DoWork,(void*)new int(i)) != 0)
      {
        //perror("worker create is error");
      }
      //sleep(1);
  }  

  for(int i = 0;i<5;i++)
  {
    pthread_join(worker[i],nullptr);
    std::cout << i << "is exit" << std::endl;
  }
  pthread_cond_destroy(&Signal);
  pthread_join(boos,nullptr);

  return 0;
}

